import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:short_drama/models/WalletCardModel.dart';
import 'package:short_drama/models/wallet_model.dart';
import 'package:short_drama/pages/mine/bind.dart';
import 'package:short_drama/pages/widgets/dialog.dart';
import 'package:short_drama/utils/colors.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:short_drama/utils/float.dart';
import 'package:short_drama/utils/http_util.dart';
import '../../models/bank_card_info_model.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

class WalletPage extends StatefulWidget {
  const WalletPage({Key? key}) : super(key: key);

  State<WalletPage> createState() => _WalletPageState();
}

class _WalletPageState extends State<WalletPage> {
  final PageController _pageController = PageController(viewportFraction: 0.8);
  final RefreshController _controller = RefreshController();
  int _currentPage = 1;
  int _itemCount = 4;
  int _selectcard = 0;
  String urlKey = '';
  String account_no = '';
  List<WalletMonthData> _listDatas = [];
  List<WalletCardModel>? _cardDatas;
  bool _isLoading = true;
  bool _isCarding = true;

  @override
  void initState() {
    super.initState();
    _fetchCardData(true);
    _queryInfo();
  }

  Future<void> _queryInfo() async {
    try {
      final result = await HttpUtil().get(
        'member/cashout_account/firstinfo',
        params: {"account_type": 'bank'},
      );
      final dynamic responseData = result.data['data'];
      if (responseData != null) {
        BankCardInfoModel value = BankCardInfoModel.fromJson(responseData);
        account_no = value.account_no ?? '';
      }
    } catch (e) {
      EasyLoading.showToast('请求失败');
    }
    EasyLoading.dismiss();
  }

  Future<void> _fetchListData() async {
    try {
      final data = await WalletViewModel().fetchProfitData(
        key: urlKey,
        page: _currentPage,
      );
      _controller.loadComplete();
      setState(() {
        if (data!.isNotEmpty) {
          if (data.length > 0) {
            _listDatas!.addAll(data);
          }
        }
        _isLoading = false;
      });
    } catch (e) {
      print('获取数据失败${e}');
      _controller.loadComplete();
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _fetchCardData(bool state) async {
    try {
      final data = await WalletViewModel.fetchProfitCardData();
      setState(() {
        _cardDatas = data;
        if (_cardDatas != null) {
          WalletCardModel model = _cardDatas!.first;
          urlKey = model.key;
          if (state) {
            _fetchListData();
          }
        }

        _isCarding = false;
      });
    } catch (e) {
      print('获取数据失败');
      setState(() {
        _isCarding = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ClientColors.ff0a0f12,
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white),
        leading: IconButton(
          onPressed: () => {Get.back()},
          icon: Icon(Icons.arrow_back_ios),
        ),
        actions: [
          GestureDetector(
            onTap: () {
              Get.to(() => BindPage());
            },
            child: Container(
              margin: EdgeInsets.only(right: 10),
              child: Text(
                '绑定银行卡',
                style: TextStyle(fontSize: 14, color: ClientColors.ff4abc9c),
              ),
            ),
          ),
        ],
        centerTitle: false,
        titleSpacing: FloatConstance.navBarSpace,
        backgroundColor: ClientColors.odffffff,
        title: Text(
          '我的钱包',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          //功能卡片
          Container(
            margin: EdgeInsets.only(top: 20, bottom: 20),
            height: 140,
            child:
                _isCarding
                    ? Center(child: CircularProgressIndicator())
                    : AnimatedBuilder(
                      animation: _pageController,
                      builder: (context, child) {
                        return PageView.builder(
                          controller: _pageController,
                          itemCount: _itemCount,
                          itemBuilder:
                              (context, index) => _buildCard(context, index),
                          onPageChanged: (value) {
                            _selectcard = value;
                            _listDatas = [];
                            _currentPage = 1;
                            WalletCardModel model = _cardDatas![value];
                            urlKey = model.key;
                            _fetchListData();
                          },
                        );
                      },
                    ),
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Container(
                width: 4,
                height: 16,
                margin: EdgeInsets.only(left: 8),
                decoration: BoxDecoration(
                  color: ClientColors.ff0b9970,
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              Container(
                margin: EdgeInsets.only(left: 8),
                child: Text(
                  '明细',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.white,
                    fontWeight: FontWeight.bold,
                  ),
                ),
              ),
              Expanded(child: Container()),
            ],
          ),
          SizedBox(height: 10),
          // 积分列表
          Expanded(
            child: SmartRefresher(
              controller: _controller,
              enablePullUp: true,
              enablePullDown: false,
              onLoading: () {
                _currentPage++;
                _fetchListData();
              },
              child:
                  _isLoading
                      ? Center(child: CircularProgressIndicator())
                      : Container(
                        padding: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                          color: ClientColors.odffffff,
                          borderRadius: BorderRadius.circular(10),
                        ),
                        child: ListView.builder(
                          shrinkWrap: true,
                          physics: const NeverScrollableScrollPhysics(),
                          itemCount: _listDatas?.length ?? 0,
                          itemBuilder: (content, index) {
                            final item = _listDatas![index];
                            return SizedBox(
                              height: 50,
                              child: Column(
                                children: [
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceBetween,
                                    children: [
                                      SizedBox(
                                        height: 32,
                                        width: 32,
                                        child: Image.asset(
                                          'assets/images/icon_wallet1.png',
                                        ),
                                      ),
                                      SizedBox(width: 10),
                                      Expanded(
                                        child: Column(
                                          crossAxisAlignment:
                                              CrossAxisAlignment.center,
                                          children: [
                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: [
                                                Text(
                                                  item.fromTypeName,
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 15,
                                                  ),
                                                ),
                                                Text(
                                                  '${item.accountData}',
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 15,
                                                  ),
                                                ),
                                              ],
                                            ),

                                            Row(
                                              mainAxisAlignment:
                                                  MainAxisAlignment
                                                      .spaceBetween,
                                              children: [
                                                Text(
                                                  item.createTime,
                                                  style: TextStyle(
                                                    color:
                                                        ClientColors.aaffffff,
                                                    fontSize: 11,
                                                  ),
                                                ),
                                                Expanded(child: Container()),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                ],
                              ),
                            );
                          },
                        ),
                      ),
            ),
          ),
          const Text(''),
        ],
      ),
    );
  }

  Widget _buildCard(BuildContext context, int index) {
    double pageOffset = 1;
    double scale = 1 - (pageOffset * 0.1).clamp(0.0, 0.08);
    if (_cardDatas == null || _cardDatas!.length == 0) {
      return Container();
    }
    final item = _cardDatas![index];
    return TweenAnimationBuilder<double>(
      tween: Tween(begin: scale, end: scale),
      duration: Duration(milliseconds: 200),
      builder: (context, value, child) {
        return Transform.scale(
          scale: (_selectcard == index) ? 1 : value,
          child: Card(
            elevation: 6,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            child: Container(
              height: 80,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(16),
                image: DecorationImage(
                  image: AssetImage('assets/images/icon_wallet_one.png'),
                  fit: BoxFit.cover,
                ),
              ),
              child: Stack(
                children: [
                  Positioned(
                    top: 14,
                    left: 18,
                    child: Text(
                      item.cardName,
                      style: TextStyle(fontSize: 15, color: Colors.black),
                    ),
                  ),
                  Positioned(
                    top: 40,
                    left: 18,
                    child: Text(
                      '${item.value}',
                      style: TextStyle(
                        fontSize: 26,
                        fontWeight: FontWeight.bold,
                        color: Colors.black,
                      ),
                    ),
                  ),
                  Positioned(
                    child: Column(
                      children: [
                        Expanded(child: Container()),
                        (item.isShowWithdraw == 1)
                            ? Row(
                              children: [
                                Expanded(child: Container()),
                                GestureDetector(
                                  onTap: () {
                                    _showDialog(
                                      item.key ?? '',
                                      item.value ?? 0,
                                      '兑换',
                                    );
                                  },
                                  child: Container(
                                    height: 26,
                                    width: 60,
                                    margin: EdgeInsets.only(
                                      right: 12,
                                      bottom: 12,
                                    ),
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(13),
                                      color: ClientColors.ff3992f8,
                                    ),
                                    child: Text(
                                      '兑换',
                                      style: TextStyle(
                                        fontSize: 13,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ),
                                GestureDetector(
                                  onTap: () {
                                    _showDialog(
                                      item.key ?? '',
                                      item.value ?? 0,
                                      '提现',
                                    );
                                  },
                                  child: Container(
                                    margin: EdgeInsets.only(
                                      right: 12,
                                      bottom: 12,
                                    ),
                                    height: 26,
                                    width: 60,
                                    alignment: Alignment.center,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(13),
                                      color: ClientColors.ff4abc9c,
                                    ),
                                    child: Text(
                                      '提现',
                                      style: TextStyle(
                                        fontSize: 13,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            )
                            : Container(),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  _showDialog(String key, int value, String title) async {
    final itemDou = _cardDatas![0];
    await Get.dialog(
      CustomDialog(
        type: key,
        dou: itemDou.value,
        value: value,
        title: title,
        account_no: account_no,
        confirm: () {
          _fetchCardData(false);
        },
      ),
      barrierDismissible: false,
    );
  }
}
